package com.example.demo.Controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.TreeMap;

@RestController
public class VisitController {

    private static final String FILE_PATH = "src/main/resources/static/files/uv.json";
    private final ObjectMapper objectMapper = new ObjectMapper();

    // 记录访问
    @GetMapping("/visit")
    public String recordVisit() {
        updateVisitCount();
        return "Visit recorded successfully!";
    }

    // 获取今日访问次数
    @GetMapping("/today-visits")
    public int getTodayVisits() {
        TreeMap<String, Integer> visitData = readVisitData();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String today = sdf.format(new Date());
        return visitData.getOrDefault(today, 0);
    }

    // 获取所有访问记录
    @GetMapping("/get-all-visits")
    public Map<String, Integer> getAllVisits() {
        return readVisitData();
    }

    // 更新访问次数并保存到文件
    private void updateVisitCount() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String today = sdf.format(new Date());

        // 读取现有的访问数据
        TreeMap<String, Integer> visitData = readVisitData();

        // 更新访问次数
        if (visitData.containsKey(today)) {
            visitData.put(today, visitData.get(today) + 1);
        } else {
            visitData.put(today, 1);
        }

        // 将更新后的数据写回文件
        writeVisitData(visitData);
    }

    // 读取访问数据
    private TreeMap<String, Integer> readVisitData() {
        TreeMap<String, Integer> visitData = new TreeMap<>();
        File file = new File(FILE_PATH);

        try {
            if (file.exists()) {
                visitData = objectMapper.readValue(file, TreeMap.class);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return visitData;
    }

    // 写入访问数据
    private void writeVisitData(TreeMap<String, Integer> visitData) {
        File file = new File(FILE_PATH);
        try {
            if (!file.exists()) {
                file.getParentFile().mkdirs();
                file.createNewFile();
            }
            objectMapper.writerWithDefaultPrettyPrinter().writeValue(file, visitData);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}